import 'dart:math';

import 'package:flutter/material.dart';

import 'hc_regexp_util.dart';

class HcStringUtil {
  const HcStringUtil._();

  //判断字符串是否为base64
  static bool checkBase64(String str) {
    RegExp base64Head = RegExp(r"data:\S+/\S+;base64,");
    //如果默认是64的头 那么就返回true
    if (HcRegexpUtil.customRegexp(base64Head, str)) {
      return true;
    }
    //切割base64取尾段
    List<String> splitList = str.split(',');
    str = splitList[splitList.length - 1];
    return HcRegexpUtil.checkIsBase64(str);
  }

  /// 首字母大写
  static String capitalizeStr(String? str) {
    if (str == null || str.isEmpty) {
      return "";
    }
    List<String> splitList = str.trim().split(" ");
    for (int i = 0; i < splitList.length; i++) {
      String str = splitList[i];
      splitList[i] = "${str[0].toUpperCase()}${str.substring(1)}";
    }
    return splitList.join(" ");
  }

  /// 格式化姓名
  static String formatterAvatarName(String? name) {
    if (name == null || name.isEmpty) return '';
    if (name.length < 3) return name.toUpperCase();
    String chinese = name.replaceAll(RegExp(r'[^\u4e00-\u9fa5]'), '');
    if (chinese.isNotEmpty) {
      return chinese.substring(max(0, chinese.length - 2));
    }
    String english = capitalizeStr(name).replaceAll(RegExp(r'[^A-Z]'), '');
    return english.substring(max(0, english.length - 2));
  }

  static Size boundingTextSize(
      BuildContext context, String text, TextStyle style,
      {int maxLines = 2 ^ 31,
      double maxWidth = double.infinity,
      textDirection = TextDirection.ltr}) {
    if (text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        locale: Localizations.localeOf(context),
        textDirection: textDirection,
        text: TextSpan(text: text, style: style),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  /// 获取文字信息
  static TextPainter getTextInfo(
      {required BuildContext context,
      required String text,
      required TextStyle style,
      int maxLines = 2 ^ 23,
      double width = double.infinity,
      String? ellipsis,
      textDirection = TextDirection.ltr}) {
    TextSpan span = TextSpan(text: text, style: style);
    return TextPainter(
      locale: Localizations.localeOf(context),
      text: span,
      maxLines: maxLines,
      ellipsis: ellipsis,
      textDirection: textDirection,
    )..layout(maxWidth: width);
  }

  ///翻转文字
  static String reverseString(String str) {
    return str.split("").reversed.join();
  }
}
